<template>
  <div class="app-container">
    <el-form :model="arr" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="商品名称" prop="productName">
        <el-input
          v-model="arr.productName"
          placeholder="请输入商品名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品货号" prop="productNo">
        <el-input
          v-model="arr.productNo"
          placeholder="请输入商品货号"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="商品分类" prop="classify">
        <el-cascader
          style="width: 100%"
          v-model="classifyOptionValue"
          clearable
          :props="{'value': 'id', 'label': 'classifyName'}"
          :options="classifyOptions"></el-cascader>
      </el-form-item>

      <el-form-item label="商品品牌" prop="brand">
        <el-select
          v-model="arr.status"
          placeholder="请选择"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="brand in productBrand"
            :key="brand.id"
            :label="brand.brandName"
            :value="brand.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:role:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:role:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:role:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:role:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="productList"></right-toolbar>
    </el-row>

    <el-table :data="productInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品编号" prop="id" width="120" />
      <el-table-column label="商品图片" width="180">
        <template slot-scope="scope">
          <el-image :src="scope.row.bgImg"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" prop="productName" width="120" />
      <el-table-column label="价格" prop="salePrice" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="排序" prop="productSort" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="库存" prop="stock" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="上架" align="center" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isPutaway"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="新品" align="center" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isNew"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="推荐" align="center" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isPutaway"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="getProductDetailById(scope.row.id)"
            v-hasPermi="['system:role:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:role:remove']"
          >删除</el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['system:role:edit']">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleDataScope" icon="el-icon-circle-check"
                                v-hasPermi="['system:role:edit']">数据权限</el-dropdown-item>
              <el-dropdown-item command="handleAuthUser" icon="el-icon-user"
                                v-hasPermi="['system:role:edit']">分配用户</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="arr.pageNum"
      :limit.sync="arr.pageSize"
      @pagination="productList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-steps :active="active" finish-status="success">
        <el-step title="填写商品信息"></el-step>
        <el-step title="填写商品促销"></el-step>
        <el-step title="填写商品属性"></el-step>
      </el-steps>

      <el-form v-if="active==0" :model="productInfo" label-width="100px">
        <el-form-item label="商品分类" prop="classify">
          <el-cascader
            style="width: 100%"
            v-model="classifyOptionValue"
            clearable
            :props="{'value': 'id', 'label': 'classifyName'}"
            :options="classifyOptions"></el-cascader>
        </el-form-item>

        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="productInfo.productName" placeholder="请输入商品名称" />
        </el-form-item>

        <el-form-item label="副标题" prop="productSubHead">
          <el-input v-model="productInfo.productSubHead" placeholder="请输入商品副标题" />
        </el-form-item>

        <el-form-item label="商品品牌" prop="brand">
          <el-select
            v-model="productInfo.productBrandId"
            placeholder="请选择"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="brand in productBrand"
              :key="brand.id"
              :label="brand.brandName"
              :value="brand.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品介绍" prop="productIntroduce">
          <el-input v-model="productInfo.productIntroduce" placeholder="请输入商品介绍" />
        </el-form-item>
        <el-form-item label="商品货号" prop="productNo">
          <el-input v-model="productInfo.productNo" placeholder="请输入商品货号" />
        </el-form-item>
        <el-form-item label="计量单位" prop="productUnit">
          <el-input v-model="productInfo.productUnit" placeholder="请输入计量单位" />
        </el-form-item>
        <el-form-item label="商品重量" prop="productWeight">
          <el-input v-model="productInfo.productWeight" placeholder="请输入商品重量" />
        </el-form-item>
        <el-form-item label="排序" prop="productSort">
          <el-input v-model="productInfo.productSort" placeholder="请输入排序" />
        </el-form-item>
      </el-form>

      <el-form v-if="active==1" ref="form" :model="productInfo" label-width="100px">
        <el-form-item label="赠送积分" prop="bonusPoints">
          <el-input v-model="productInfo.bonusPoints" placeholder="请输入赠送积分" />
        </el-form-item>
        <el-form-item label="赠送成长值" prop="bonusGrowth">
          <el-input v-model="productInfo.bonusGrowth" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="积分购买限制" prop="pointsPurchase">
          <el-input v-model="productInfo.pointsPurchase" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="预告商品" prop="status">
          <el-switch
            v-model="productInfo.isAdvance"
            active-value="0"
            inactive-value="1"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="商品上架" prop="status">
          <el-switch
            v-model="productInfo.isPutaway"
            active-value="0"
            inactive-value="1"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="商品推荐" prop="status">
          新品：<el-switch
          v-model="productInfo.isNew"
          active-value="0"
          inactive-value="1"
        >
        </el-switch>
          推荐：<el-switch
          v-model="productInfo.isRecommend"
          active-value="0"
          inactive-value="1"
        >
        </el-switch>
        </el-form-item>
        <el-form-item label="详细页标题" prop="detailTitle">
          <el-input v-model="productInfo.detailTitle" placeholder="请输入详细页标题" />
        </el-form-item>
        <el-form-item label="详细页描述" prop="detailDescribe">
          <el-input v-model="productInfo.detailDescribe" placeholder="请输入详细页描述" />
        </el-form-item>
        <el-form-item label="商品关键字" prop="detailKeyWord">
          <el-input v-model="productInfo.detailKeyWord" placeholder="请输入商品关键字" />
        </el-form-item>
        <el-form-item label="商品备注" prop="detailRemark">
          <el-input v-model="productInfo.detailRemark" placeholder="请输入商品备注" />
        </el-form-item>
        <el-form-item label="选择优惠方式" prop="status">
          <el-tabs  v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="无优惠" name="first"></el-tab-pane>
            <el-tab-pane label="特惠促销" name="second">
              开始时间:<el-date-picker v-model="productInfo.specialOffersReq.startTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间"></el-date-picker><br>
              结束时间:<el-date-picker v-model="productInfo.specialOffersReq.endTime" type="datetime"  value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间"></el-date-picker><br>
              促销价格：<el-input v-model="productInfo.specialOffersReq.offersPrice" style="width: 100px;"></el-input>
            </el-tab-pane>
            <el-tab-pane label="会员价格" name="third">
              黄金会员：<el-input v-model="productInfo.shopMemberReq.goldPrice" style="width: 200px;"></el-input><br>
              白金会员：<el-input v-model="productInfo.shopMemberReq.platinumPrice" style="width: 200px;"></el-input><br>
              钻石会员：<el-input v-model="productInfo.shopMemberReq.diamondPrice" style="width: 200px;"></el-input>
            </el-tab-pane>
            <el-tab-pane label="阶梯价格" name="fourth" >
              <el-table :data="productInfo.shopLadder" height="250" border style="width: 100%">
                <el-table-column label="数量" width="180">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.ladderNum"></el-input>
                  </template>
                </el-table-column>
                <el-table-column  label="折扣" width="180">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.ladderDiscount"></el-input>
                  </template>
                </el-table-column>
                <el-table-column  label="操作">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="danger"
                      @click="handleDelete( scope.row)">删除</el-button>
                    <el-button
                      size="mini"
                      type="danger"
                      @click="handleInsert( scope.row)">添加</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="满减价格" name="five">

              <el-table :data="productInfo.fullSubtractionReq" height="250" border style="width: 100%">
                <el-table-column label="满" width="180">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.fullPrice"></el-input>
                  </template>
                </el-table-column>
                <el-table-column  label="立减" width="180">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.subtractionPrice"></el-input>
                  </template>
                </el-table-column>
                <el-table-column  label="操作">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="danger"
                      @click="handleFullSubtractionReqDelete(scope.row)">删除</el-button>
                    <el-button
                      size="mini"
                      type="danger"
                      @click="handleufllSubtractionReqInsert(scope.row)">添加</el-button>
                  </template>
                </el-table-column>
              </el-table>

            </el-tab-pane>
          </el-tabs>
        </el-form-item>
      </el-form>



      <el-form v-if="active==2" label-width="80px" :model="productInfo" >

        <el-form-item label="属性类型">
          <el-select v-model="productInfo.productTypeId" placeholder="请选择属性" clearable style="width: 240px" @change="getAttrByTyId">
            <el-option v-for="item in productTypeList" :key="item.productTypeId" :label="item.productTypeName" :value="item.productTypeId"/>
          </el-select>
        </el-form-item>

        <el-form-item label="商品规格">
          <div v-for="(value,key) in Object.entries(attrForm)" :key="key">
            {{value[1].name}}
            <el-checkbox-group v-model="checkAttrs">
              <el-checkbox v-for="item in value[1].value" @change="checkedAttrs(item,value[0])" :key="item.typeAttrId" :label="item.typeAttrValue" :value="item.typeAttrValue"/>
            </el-checkbox-group>
          </div>
          <div>
            <el-table :data="productInfo.productSkuList" height="250" border style="width: 100%">
              <el-table-column v-for="item in typeAttrArr" :prop="String(item.id)" :label="item.attrName" width="180">
              </el-table-column>

              <el-table-column  label="销售价格" width="180">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.salePrice"></el-input>
                </template>
              </el-table-column>

              <el-table-column  label="促销价格" width="180">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.promotionPrice"></el-input>
                </template>
              </el-table-column>

              <el-table-column  label="商品库存" width="180">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.stock"></el-input>
                </template>
              </el-table-column>

              <el-table-column  label="库存预警值" width="180">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.stockAlert"></el-input>
                </template>
              </el-table-column>

              <el-table-column  label="SKU编号" width="180">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.id"></el-input>
                </template>
              </el-table-column>

              <el-table-column  label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="danger"
                    @click="handleDeleteSku( scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button type="primary" @click="refreshSkuInfos" style="margin-top: 20px">刷新SKU组合列表</el-button>
          </div>
        </el-form-item>

        <el-form-item label="商品参数">
          <div v-for="(value,key) in Object.entries(attrValue)" :key="key">
            {{value[1].name}}
            <el-checkbox-group v-model="checkAttr">
              <el-checkbox v-for="item in value[1].value" :label="item.typeAttrValue" :value="item.typeAttrId" :key="item.typeAttrValue"></el-checkbox>
            </el-checkbox-group>
          </div>
        </el-form-item>

        <el-form-item label="属性图片">
          <image-upload v-model="productInfo.bgImg" :limit="2" :is-show-tip="false"/>
        </el-form-item>

        <el-form-item label="商品详情">
          <el-tabs  v-model="activeName">
            <el-tab-pane label="电脑端详情" >
              <editor v-model="productInfo.pcProductDetail" :min-height="192"/>
            </el-tab-pane>

            <el-tab-pane label="移动端详情" >
              <editor v-model="productInfo.mobileProductDetail" :min-height="192"/>
            </el-tab-pane>
          </el-tabs>
        </el-form-item>
      </el-form>

        <el-button style="margin-top: 12px;" @click="back">上一步</el-button>
        <el-button style="margin-top: 12px;" @click="next">下一步</el-button>
      <el-button v-if="active==2" style="margin-top: 12px;" @click="insert()">完成提交商品</el-button>
    </el-dialog>

  </div>
</template>

<script>
import { getRole, delRole, addRole, updateRole, dataScope, changeRoleStatus, deptTreeSelect } from "@/api/system/role";
import {
  brandList,
  getAll,
  getAttrByTyId,
  getProductDetailById,
  productList,
  saveOrUpdate,
  typeList,
  typeParameter
} from "@/api/product/info";

export default {
  name: "ProductInfo",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      active: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      aa:{},
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      productInfoList: [],
      classifyOptionValue:[],
      classifyOptions:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],
      //商品品牌
      productBrand: [

        ],
      productTypeList:[],
      // 数据范围选项
      dataScopeOptions: [
        {
          value: "1",
          label: "全部数据权限"
        },
        {
          value: "2",
          label: "自定数据权限"
        },
        {
          value: "3",
          label: "本部门数据权限"
        },
        {
          value: "4",
          label: "本部门及以下数据权限"
        },
        {
          value: "5",
          label: "仅本人数据权限"
        }
      ],
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      arr: {
        productName:null,
        productNo:null,
        classify:null,
        brand:null
      },
      bb:{},
      // 表单参数
      productInfo: {
        salePrice: 0,
        marketPrice: 0,
        inventory: 0,
        productWeight: 0,
        sort:0,
        bonusPoints:0,
        bonusGrowth:0,
        pointsPurchase:0,
        isAdvance:0,
        isPutaway:0,
        isRecommend:0,
        offersTypeId:0,
        specialOffersReq:{
          startTime:'',
          endTime:'',
          offersPrice: 0.0
        },
        shopMemberReq:{
          goldPrice:0.0,
          platinumPrice:0.0,
          diamondPrice:0.0
        },
        shopLadder:[
          { ladderNum: 0, ladderDiscount: 0 },
        ],
        fullSubtractionReq:[
          { fullPrice: 0, subtractionPrice: 0 }
        ],
        productSkuList:[

        ]
      },
      activeName:"first",
      typeArr:[],
      typeAttrArr:[],
      attrForm:[],
      checkAttrs:[],
      //接口返回的初始数据
      attrRows:[],
      checkedAttrValue:{},
      parameterList:[],
      attrValue:[],
      checkAttr:[]
    };
  },
  created() {
    this.brandList();
    this.getAll();
    this.productList();
    this.typeList();
  },
  mounted() {
  },
  methods: {
    getProductDetailById(id){
      this.open = true;
      getProductDetailById(id).then(res=>{
        this.productInfo = res.data
        console.log(this.productInfo)
      })
    },
    insert(){
      this.productInfo.productClassIfyId= (this.classifyOptionValue)[0]
      saveOrUpdate(this.productInfo).then(res=>{
        if(res.code == 200){
          this.$message.success('' || '操作成功')
          this.productList();
        }
      })
    },
    getAttrByTyId(){
      typeParameter(this.productInfo.productTypeId).then(res=>{
        this.attrValue = [];
        this.parameterList = res.data
        this.parameterList.forEach(item=>{
          //构建属性载体
          //规格载体
          const object = {};
          object.name = item.attrName;
          object.value = item.productTypeAttrValueReq;
          this.attrValue[item.id] = object;
        })
      })
      getAttrByTyId(this.productInfo.productTypeId).then(res=>{
        //初始化规格列表
        this.attrForm = [];
        this.typeAttrArr = res.data
        //去除typeAttrArr集合中的id作为key，
        this.typeAttrArr.forEach(item=>{
          //构建属性载体
          //规格载体
          const attrBody = {};
          attrBody.name = item.attrName;
          attrBody.value = item.productTypeAttrValueReq;
          this.attrForm[item.id] = attrBody;
        })
      })
    },
    //存储已选择的规格信息
    checkedAttrs(attrItem,id){
      //遍历checkedAttrValue，判断key是否等于id这个参数，如果等于，则取出id对应的value值，value是一个数组，将attrItem添加到数组
      if (this.checkedAttrValue[id]) {
        //判断id对应的value数组中是否包含了attrItem.typeAttrValue，如果包含，则删除，如果不包含，则添加
        //以达到选择或取消的效果
        const index = this.checkedAttrValue[id].indexOf(attrItem.typeAttrValue);
        if (index > -1) {
          this.checkedAttrValue[id].splice(index, 1); // 删除
        } else {
          this.checkedAttrValue[id].push(attrItem.typeAttrValue); // 添加
        }

      }else {
        this.checkedAttrValue[id] = Array(attrItem.typeAttrValue)
      }
    },
    refreshSkuInfos(){
      this.productInfo.productSkuList = [];
      //给列表数据 skuInfos赋值
      const keys = Object.keys(this.checkedAttrValue);

      for (let i = 0; i < this.checkedAttrValue[keys[0]].length; i++) {
        for (let j = 0; j < this.checkedAttrValue[keys[1]].length; j++) {
          const item = {};
          item[keys[0]] = this.checkedAttrValue[keys[0]][i];
          item[keys[1]] = this.checkedAttrValue[keys[1]][j];
          this.productInfo.productSkuList.push(item);
        }
      }
    },
    handleFullSubtractionReqDelete(index, row){
      this.productInfo.fullSubtractionReq.splice(index, 1);
    },
    handleufllSubtractionReqInsert(){
      this.productInfo.fullSubtractionReq.push({
        fullPrice: 0, // 初始值
        subtractionPrice: 0, // 初始值
      });
    },
    handleDelete(index, row) {
      this.productInfo.shopLadder.splice(index, 1);
    },
    handleInsert(){
      this.productInfo.shopLadder.push({
        ladderNum: 0,
        ladderDiscount: 0,
      })
    },
    handleClick(tab){
      this.productInfo.offersType=tab.index
    },
    next() {
      if (this.active++ > 2) this.active = 0;
    },
    back() {
      if(this.active-- == 0) this.active = 0;
    },
    productList() {
      productList(this.arr).then(
        response => {
         console.log(response)
          this.productInfoList = response.data
        }
      )
    },
    brandList(){
      brandList(this.aa).then(
        response => {
          this.productBrand=response.data;
        }
      )
    },
    typeList(){
      typeList().then(
        response => {
          this.productTypeList=response.data;
        }
      )
    },
    getAll(){
      getAll().then(
        response => {
          this.classifyOptions=response.data;
        }
      )
    },


    // 角色状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.roleName + '"角色吗？').then(function() {
        return changeRoleStatus(row.roleId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.menuExpand = false,
      this.menuNodeAll = false,
      this.deptExpand = true,
      this.deptNodeAll = false,
      this.form = {
        roleId: undefined,
        roleName: undefined,
        roleKey: undefined,
        roleSort: 0,
        status: "0",
        menuIds: [],
        deptIds: [],
        menuCheckStrictly: true,
        deptCheckStrictly: true,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.arr.pageNum = 1;
      this.productList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.roleId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleDataScope":
          this.handleDataScope(row);
          break;
        case "handleAuthUser":
          this.handleAuthUser(row);
          break;
        default:
          break;
      }
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      } else if (type == 'dept') {
        let treeList = this.deptOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions: []);
      } else if (type == 'dept') {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions: []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'menu') {
        this.form.menuCheckStrictly = value ? true: false;
      } else if (type == 'dept') {
        this.form.deptCheckStrictly = value ? true: false;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加角色";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.form=row;
      this.open=true;
    },
    /** 选择角色权限范围触发 */
    dataScopeSelectChange(value) {
      if(value !== '2') {
        this.$refs.dept.setCheckedKeys([]);
      }
    },
    /** 分配数据权限操作 */
    handleDataScope(row) {
      this.reset();
      const deptTreeSelect = this.getDeptTree(row.roleId);
      getRole(row.roleId).then(response => {
        this.form = response.data;
        this.openDataScope = true;
        this.$nextTick(() => {
          deptTreeSelect.then(res => {
            this.$refs.dept.setCheckedKeys(res.checkedKeys);
          });
        });
        this.title = "分配数据权限";
      });
    },
    /** 分配用户操作 */
    handleAuthUser: function(row) {
      const roleId = row.roleId;
      this.$router.push("/system/role-auth/user/" + roleId);
    },
    // /** 提交按钮 */
    // submitForm: function() {
    //   this.$refs["form"].validate(valid => {
    //     if (valid) {
    //       this.form.menuIds = this.getMenuAllCheckedKeys();
    //       saveOrUpdate(this.form).then(response => {
    //         this.$modal.msgSuccess("操作成功");
    //         this.open = false;
    //         this.productList();
    //       });
    //     }
    //   });
    // },
    /** 提交按钮（数据权限） */
    submitDataScope: function() {
      if (this.form.roleId != undefined) {
        this.form.deptIds = this.getDeptAllCheckedKeys();
        dataScope(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.openDataScope = false;
          this.productList();
        });
      }
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('system/role/export', {
        ...this.arr
      }, `role_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
